package com.way.fileexplorer.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.way.fileexplorer.R;
import com.way.fileexplorer.adapters.CopyDestListAdapter;
import com.way.fileexplorer.adapters.SearchListAdapter;
import com.way.fileexplorer.util.ActivityUtils;
import com.way.fileexplorer.util.FileSearch;
import com.way.fileexplorer.util.FileSort;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.FileUtil;
import com.way.fileexplorer.util.Slog;
import com.way.fileexplorer.util.StorageUtil;

public class FileSearchResultActivity extends Activity {
    private SearchListAdapter mAdapter;
    private ListView mListView = null;
    private View mEmptyView = null;
    private SearchTask mSearchTask = new SearchTask();
    private static boolean mIsSearching;
    private List<File> mSearchLoaction= new ArrayList<File>();
    private String mSearchKey;
    private ArrayList<Integer> mSearchType;
    public static final int MENU_COPY = 1;
    public static final int MENU_CUT = 2;
    public static final int MENU_DELETE = 3;
    public static final int MENU_CLEAR = 4;
    public static final int MENU_SHARE = 5;
    public static final int MENU_RENAME = 6;
    public static final int MENU_DETAIL = 7;
    private Context mContext;
    private ProgressDialog mWaitDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_searchresult);
        mContext = this;
        mListView = (ListView) this.findViewById(R.id.list_paste);
        mEmptyView = (View) this.findViewById(R.id.emptyView);
        mAdapter = new SearchListAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                mAdapter.execute(arg2);
            }

        });
        mListView.setOnCreateContextMenuListener(mFileListOnCreateContextMenuListener);

        Intent data = getIntent();
        if (null != data) {
        	Bundle bun = data.getBundleExtra(FileSearch.SEARCH_ATTACH);
        	if(bun != null){
        		mSearchKey = bun.getString(FileSearch.SEARCH_KEY);
        		mSearchType = bun.getIntegerArrayList(FileSearch.SEARCH_TYPE);
        		int searchLocation = bun.getInt(FileSearch.SEARCH_LOCATION);
        		getSearchLoaction(searchLocation);
        		if(mSearchKey != null && !mSearchKey.isEmpty() && this.mSearchLoaction != null){
        			mSearchTask = new SearchTask();
        			mSearchTask.execute("");
        		}
        	}
        } else {
            finish();
        }
    }

    public void getSearchLoaction(int type) {    	
	if(mSearchLoaction == null)
		return;
        mSearchLoaction.clear();
    	switch(type){
    	case FileSearch.SEARCH_ALL:
    		mSearchLoaction.add(StorageUtil.getExternalStorage()); 
    		mSearchLoaction.add(StorageUtil.getInternalStorage()); 
    		break;
    	case FileSearch.SEARCH_EXTERNAL:
    	    mSearchLoaction.add(StorageUtil.getExternalStorage()); 
    		break;
    	case FileSearch.SEARCH_INTERNAL:
    	    mSearchLoaction.add(StorageUtil.getInternalStorage());
    		break;
    	}
	}
    
    class SearchTask extends AsyncTask<String, Cursor, String> {

		SearchTask() {
		}

		@Override
		protected String doInBackground(String... params) {
			searchFile(mSearchLoaction);
			mIsSearching = false;
			return null;
		}

		void initSearch() {

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mAdapter.getFileList().clear();
			Slog.d("onPreExecute");
			mIsSearching = true;
			mWaitDialog = new ProgressDialog(mContext);
			mWaitDialog.setTitle(R.string.dialog_hint_title);
			mWaitDialog.setMessage(mContext.getResources().getString(R.string.dialog_hint_msg));
			mWaitDialog.setCancelable(false);
			mWaitDialog.show();
		}

		@Override
		protected void onProgressUpdate(Cursor... values) {
			super.onProgressUpdate(values);
			mAdapter.getFileList().clear();
			if (values != null && values.length != 0) {
			    for(Cursor cursor:values){
			        while(cursor.moveToNext()){
	                    File file = new File(cursor.getString(0));
	                    int fileType = FileType.getFileType(FileSearchResultActivity.this).getFileType2(file);
	                    if(mSearchType != null && mSearchType.size()!=0){
	                        if(mSearchType.contains(fileType)){
	                            if(!mAdapter.getFileList().contains(file) && file.exists()){
	                                mAdapter.getFileList().add(file);
	                            }
	                        }
	                    }else{
	                        if(!mAdapter.getFileList().contains(file) && file.exists()){
                                mAdapter.getFileList().add(file);
                            }
	                    }
	                }
			    }
                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        FileSort.getFileListSort().sort(mAdapter.getFileList());
                        mHandler.post(new Runnable(){
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                mAdapter.notifyDataSetChanged();
                                mListView.setEmptyView(mEmptyView);
                                mWaitDialog.dismiss();
                            }
                        });
                    }
                }).start();
			}
		}
		
		void searchFile(List<File> fileSet){
		    Uri uri = MediaStore.Files.getContentUri("external");
		    String[] projection = new String[]{MediaStore.Files.FileColumns.DATA};
		    String selection1 = MediaStore.Files.FileColumns.TITLE + " like '%" + mSearchKey + "%' AND " +  "format = 12289";
		    String selection2 = MediaStore.Files.FileColumns.TITLE + " like '%" + mSearchKey + "%' AND " +  "format != 12289";
            if(fileSet.size() == 1){
                selection1 += " AND " + MediaStore.Files.FileColumns.DATA + " like '" + fileSet.get(0).getPath() + "%'" ;
                selection2 += " AND " + MediaStore.Files.FileColumns.DATA + " like '" + fileSet.get(0).getPath() + "%'" ;
            }
            final SharedPreferences sortPreference =  mContext.getSharedPreferences(
                    FileSort.FILE_SORT_KEY, 0);
            int sort = sortPreference.getInt(FileSort.FILE_SORT_KEY, FileSort.SORT_BY_NAME);
            String sortBy = FileSort.getOrderStr(sort);
	        Cursor cursor1 = mContext.getContentResolver().query(uri, projection, selection1, null, sortBy);
	        Cursor cursor2 = mContext.getContentResolver().query(uri, projection, selection2, null, sortBy);
            Cursor[] cursor = new Cursor[2];
            cursor[0] = cursor1;
            cursor[1] = cursor2;
            publishProgress(cursor);
		}
	}
    
    @Override
    public void onBackPressed() {
        mListView.setEmptyView(null);
        if (mAdapter.popupFolder()) {
            finish();
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }
    
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case FileUtil.REFREAH_FILELIST:
                if(mAdapter.getInSearchUi()){
                    searchFile();
                }else{
                    File file = mAdapter.getCurrentPath();
                    mAdapter.refresh(file);
                }
                break;
            default:
                break;
            }
        };
    };
    
    public void searchFile(){
        Intent data = getIntent();
        Bundle bun = data.getBundleExtra(FileSearch.SEARCH_ATTACH);
        if(bun != null){
            mSearchKey = bun.getString(FileSearch.SEARCH_KEY);
            int searchLocation = bun.getInt(FileSearch.SEARCH_LOCATION);
            getSearchLoaction(searchLocation);
            if(mSearchKey != null && !mSearchKey.isEmpty() && this.mSearchLoaction != null){
                mSearchTask = new SearchTask();
                mSearchTask.execute("");
            }
        }
    }
    
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ActivityUtils.startPasteMode(which);
            finish();
        }
    };
    
    private final OnCreateContextMenuListener mFileListOnCreateContextMenuListener = new OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo) {
            AdapterView.AdapterContextMenuInfo info;
            try {
                info = (AdapterView.AdapterContextMenuInfo) menuInfo;
            } catch (ClassCastException e) {
                return;
            }
            final int position = info.position;
            File selectedFile = (File) mAdapter.getItem(position);
            FileListMenuClickListener l = new FileListMenuClickListener(
                    selectedFile);
            menu.add(0, MENU_COPY, 0, R.string.menu_copy)
                    .setOnMenuItemClickListener(l);
            menu.add(0, MENU_CUT, 0, R.string.menu_cut)
                    .setOnMenuItemClickListener(l);
            menu.add(0, MENU_DELETE, 0, R.string.operate_delete)
                    .setOnMenuItemClickListener(l);
            if (selectedFile.isDirectory()) {
                menu.setHeaderTitle(R.string.folder_option);
                menu.add(0, MENU_CLEAR, 0, R.string.operate_clear)
                        .setOnMenuItemClickListener(l);
            } else {
                menu.setHeaderTitle(R.string.file_option);
                menu.add(0, MENU_SHARE, 0, R.string.operate_share)
                        .setOnMenuItemClickListener(l);
            }
            menu.add(0, MENU_RENAME, 0, R.string.operate_rename)
                    .setOnMenuItemClickListener(l);
            menu.add(0, MENU_DETAIL, 0, R.string.operate_viewdetails)
                    .setOnMenuItemClickListener(l);

        }
    };
    
    private final class FileListMenuClickListener implements
            MenuItem.OnMenuItemClickListener {
        private File mClickedFile;

        public FileListMenuClickListener(File selectedFile) {
            mClickedFile = selectedFile;
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (mClickedFile == null) {
                return false;
            }

            switch (item.getItemId()) {
            case MENU_COPY:
                FileUtil.copy(mContext, mClickedFile, false);
                if(StorageUtil.getExternalStorageState().equals("mounted")){
                    Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle(R.string.select_destination);
                    BaseAdapter adapter = new CopyDestListAdapter();
                    builder.setAdapter(adapter, listener);
                    builder.create().show();
                }else{
                	ActivityUtils.startPasteMode(0);
                    finish();
                }
                
                return true;
            case MENU_CUT:
                FileUtil.copy(mContext, mClickedFile, true);
                if(StorageUtil.getExternalStorageState().equals("mounted")){
                	ActivityUtils.showDestSelectDialog(mContext, listener);
                }else{
                	ActivityUtils.startPasteMode(0);
                    finish();
                }
                return true;
            case MENU_DELETE:
                new AlertDialog.Builder(mContext)
                .setTitle(R.string.operate_delete)
                .setMessage(R.string.confirm_delete)
                .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                                FileUtil.deleteSingleFile(mClickedFile, FileSearchResultActivity.this, mHandler);
                                            }
                                })
                                .setNegativeButton(android.R.string.cancel, null)
                                .show();
                return true;
            case MENU_CLEAR:
                new AlertDialog.Builder(mContext)
                        .setTitle(R.string.operate_clear)
                        .setMessage(R.string.msg_issure_clear)
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                // TODO Auto-generated method
                                                // stub
                                                FileUtil.clear(mClickedFile, FileSearchResultActivity.this);
                                                mHandler.obtainMessage(
                                                        FileUtil.REFREAH_FILELIST)
                                                        .sendToTarget();
                                            }
                                        }).start();
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                return true;
            case MENU_SHARE:
                Intent intent=new Intent(Intent.ACTION_SEND);
                String type = FileType.getFileType(FileSearchResultActivity.this).getTypeByFile(mClickedFile);
                Uri uri = Uri.parse("file://" + mClickedFile.getPath());
                intent.setType(type);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivity(Intent.createChooser(intent, mContext.getResources().getString(R.string.operate_share)));
                return true;
            case MENU_RENAME:
                FileUtil.rename(mClickedFile,mAdapter, FileSearchResultActivity.this);
                return true;
            case MENU_DETAIL:
                FileUtil.viewDetails(mClickedFile, FileSearchResultActivity.this);
                return true;
            default:
                return false;
            }
        }

    }
}
